package com.lms.common.web.config;

import com.alibaba.fastjson2.JSON;
import com.lms.common.pure.http.HttpResponse;
import com.lms.common.web.annotation.IgnoreResponseAdvice;
import jakarta.annotation.Nonnull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * <h1>实现统一响应</h1>
 *
 * @author 王天瑞
 * @since 1.0
 * @version 1.0
 */
@RestControllerAdvice(value = "com.lms")
@Slf4j
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {
    /**
     * <h2>判断是否需要对响应进行处理</h2>
     *
     * @param methodParameter 请求方法对象
     * @param converterType 处理类
     * @return 是否需要进行响应处理
     */
    @Override
    public boolean supports(MethodParameter methodParameter, @Nonnull Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> declaringClass = methodParameter.getDeclaringClass();
        Method method = methodParameter.getMethod();
        Class<IgnoreResponseAdvice> type = IgnoreResponseAdvice.class;
        return !(declaringClass.isAnnotationPresent(type) || Objects.requireNonNull(method).isAnnotationPresent(type));
    }

    /**
     * <h2>对请求响应结果进行封装</h2>
     *
     * @param body 原生返回数据值
     * @param returnType 返回类型
     * @param selectedContentType 用不到
     * @param selectedConverterType 用不到
     * @param request 用不到
     * @param response 用不到
     * @return 请求响应结果
     */
    @Override
    public Object beforeBodyWrite(Object body, @Nonnull MethodParameter returnType, @Nonnull MediaType selectedContentType, @Nonnull Class<? extends HttpMessageConverter<?>> selectedConverterType, @Nonnull ServerHttpRequest request, @Nonnull ServerHttpResponse response) {
        HttpResponse<Object> result = HttpResponse.ok();
        if (body instanceof HttpResponse) {
            return body;
        }
        result.setData(body);
        if (body instanceof String) {
            return JSON.toJSONString(result);
        }
        return result;
    }

//    /**
//     * <h2>未定义异常</h2>
//     * @param e 异常对象
//     * @return 异常处理结果
//     */
//    @ExceptionHandler(value = Exception.class)
//    public HttpResponse<Object> handleException(Exception e) {
//        log.error("请求响应异常!", e);
//        return HttpResponse.error();
//    }
}
